package com.curry.apiprovider.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.apache.log4j.Logger;

public class Machine {

	private static final Logger logger = Logger.getLogger(Machine.class);

	public static String getMACAddress() {
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip;
			byte[] mac = null;
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
					continue;
				} else {
					mac = netInterface.getHardwareAddress();
					if(mac != null) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < mac.length; i++) {
							sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));

						}
						if (sb.length() > 0) return sb.toString();
					}
				}
			}
		} catch(Throwable th) {
			logger.warn("<<<<<< Get MAC Address Fail", th);
		}
		return null;
	}

	public static String getIPAddress() {
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip;
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
					continue;
				} else {
					Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
					while (addresses.hasMoreElements()) {
						ip = addresses.nextElement();
						if (ip != null && ip instanceof Inet4Address) {
							return ip.getHostAddress();
						}
					}
				}
			}
		} catch(Throwable th) {
			logger.warn("<<<<<< Get IP Address Fail", th);
		}
		return null;
	}
	
	public static String getLocalMac()  {
		try{
			InetAddress ia = InetAddress.getLocalHost();
			//获取网卡，获取地址
			byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
			if(mac != null) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < mac.length; i++) {
					sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
				}
				if (sb.length() > 0) return sb.toString();
			}
		} catch(Throwable th) {
			logger.warn("<<<<<< Get MAC Address Fail", th);
		}
		return null;
	}


	public static void main(String[] args) throws UnknownHostException, SocketException {
		System.out.println(getMACAddress());
		System.out.println(getLocalMac());
		System.out.println(getIPAddress());
	}
}
